import { Form, Button, DatePicker, Switch, InputNumber, Input } from 'antd';
import { useEffect } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { addadmin, changeAuth } from 'api/super';
import { dateFormat } from '@/utils/funcs';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash';
import md5 from 'js-md5';

export default function () {
	const { state }: any = useLocation();
	const navigate = useNavigate();
	const { useForm, Item } = Form;
	const [form] = useForm();
	function init() {
		if (state) {
			const defaltdata = cloneDeep(state);
			let { useEndTime, useStartTime } = defaltdata;
			useEndTime = dayjs(dateFormat(useEndTime), 'YYYY-MM-DD');
			useStartTime = dateFormat(useStartTime);
			form.setFieldsValue({ ...defaltdata, useEndTime, useStartTime, passWord: '00000000X' });
		} else
			form.setFieldsValue({
				isBan: true,
				accountLimit: 5,
				cardArrayLimitCount: 10,
				cardTypeLimitCount: 100,
				useEndTime: dayjs(dateFormat(new Date()), 'YYYY-MM-DD'), // dateFormat(new Date())
				useStartTime: dateFormat(new Date()),
			});
	}
	useEffect(() => {
		init();
	}, []);

	async function onFinish(formdata: any) {
		if (state) {
			const userid = formdata.id;
			await changeAuth({ ...formdata, userid });
		} else {
			const passWord = md5(formdata.passWord);
			await addadmin({ ...formdata, passWord });
		}

		// init();
		navigate('../authlist');
	}

	return (
		<div>
			<Form className=' w-60' form={form} name='basic' onFinish={onFinish}>
				<Item name='id' className=' h-0'></Item>
				<Item label='账号' name='account' rules={[{ pattern: /^[a-zA-Z0-9]{6,16}$/, message: '6-16位数字/字母' }]}>
					<Input placeholder='账号/用户名' disabled={state} />
				</Item>
				<Item
					label='密码'
					name='passWord'
					rules={[
						{
							pattern: /^(?=.*[0-9])(?=.*[a-zA-Z~!@#$%^&*._?\x20])[0-9A-Za-z~!@#$%^&*._?\x20]{8,16}$/,
							message: '8-16位，包含数字和字母或特殊字符',
						},
					]}>
					<Input.Password autoComplete='new-password' placeholder='密码' disabled={state} />
				</Item>
				<Item label='禁用账号' name='isBan'>
					<Switch checkedChildren='禁用' unCheckedChildren='启用' />
				</Item>
				<Item label='限制子账号数' name='accountLimit'>
					<InputNumber min={1} />
				</Item>
				<Item label='限制可创建牌组数' name='cardArrayLimitCount'>
					<InputNumber min={1} />
				</Item>
				<Item label='限制可创建牌型数' name='cardTypeLimitCount'>
					<InputNumber min={1} />
				</Item>
				<Item label='权限开始时间' name='useStartTime'>
					<Input disabled className=' w-64' />
				</Item>
				<Item label='权限到期时间' name='useEndTime'>
					<DatePicker />
				</Item>
				<Item>
					<div className=' flex justify-end'>
						<Button type='primary' htmlType='submit'>
							提交
						</Button>
					</div>
				</Item>
			</Form>
		</div>
	);
}
